package utils;


import org.apache.commons.codec.binary.Base64;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.util.Date;

/**
 * cookies 加密解密
 * Created by weijianyu on 2017/4/23.
 */
public class CookieUtil {

    private static final Logger logger = LogManager.getLogger(CookieUtil.class);

    private static final String REGEX = ",";
    private static final String SALT = "sevenkey@10india";

    private static SecretKey convertSecretKey;
    private static Cipher cipher;

    private CookieUtil() {

    }

    static {
        try {
            // 初始化
            KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
            keyGenerator.init(56);
            SecretKey secretKey = keyGenerator.generateKey();
            byte[] bytesKey = secretKey.getEncoded();
            //key转换
            DESKeySpec keySpec = new DESKeySpec(bytesKey);
            SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
            convertSecretKey = factory.generateSecret(keySpec);
            cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        } catch (Exception e) {
            logger.error("DES 初始化失败", e);
        }
    }

    /**
     * DES 加密算法
     *
     * @param cookieInfo 加密的cookie信息
     * @return 加密后的结果 空字符串为加密失败
     */
    public static String desEncryption(String cookieInfo) {
        try {
            cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
            byte[] result = cipher.doFinal(cookieInfo.getBytes());
            return new String(Base64.encodeBase64(result), "utf-8");
        } catch (Exception e) {
            logger.error("DES加密 加密出错", e);
        }
        return "";
    }

    /**
     * DES 解密算法
     *
     * @param encryption 加密过的信息
     * @return 解密后的信息 空为解密失败
     */
    public static String desDecryption(String encryption) {
        try {
            cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
            byte[] raw = cipher.doFinal(Base64.decodeBase64(encryption));
            return new String(raw);
        } catch (Exception e) {
            logger.error("DES 解密失败", e);
        }
        return "";
    }

    /**
     * 拼接cookie 信息
     *
     * @param id   用户id
     * @param date 日期
     * @return 拼接后的cookie信息
     */
    public static String jointCookie(int id, String date) {
        StringBuilder cookie = new StringBuilder();
        cookie.append(SALT).append(REGEX).append(id).append(REGEX).append(date);
        return cookie.toString();
    }

    /**
     * 拼接cookie 信息
     *
     * @param id   用户id
     * @param date 日期
     * @return 拼接后的cookie信息
     */
    public static String jointCookie(int id, Date date) {
        return jointCookie(id, DateUtil.date2String(date, DateUtil.TOSECOND));
    }

    /**
     * 获取cookieInfo中的验证盐值
     *
     * @param cookieInfo cookieInfo
     * @return cookieInfo包含的盐值
     */
    public static String getSalt(String cookieInfo) {
        String[] infos = cookieInfo.split(REGEX);
        return infos[0];
    }

    /**
     * 获取cookieInfo中的用户id
     *
     * @param cookieInfo cookieInfo
     * @return cookieInfo包含的用户id
     */
    public static int getUserId(String cookieInfo) {
        String[] infos = cookieInfo.split(REGEX);
        return Integer.parseInt(infos[1]);
    }

    /**
     * 获取cookieInfo中的有效时间
     *
     * @param cookieInfo cookieInfo
     * @return cookieInfo包含的有效时间
     */
    public static String getEffectiveDate(String cookieInfo) {
        String[] infos = cookieInfo.split(REGEX);
        return infos[2];
    }

    /**
     * 返回盐值
     *
     * @return 盐值
     */
    public static String cookieSalt() {
        return SALT;
    }

    /**
     * 返回分隔符
     *
     * @return 分隔符
     */
    public static String cookieRegex() {
        return REGEX;
    }

}
